package Server

import (
	"encoding/json"
	"fmt"
	"log"
	"myproject/ImageHandleModel"
	"myproject/asrModel"
	"myproject/operateDB"
	"myproject/textTranslateModel"
	"net/http"
	"time"
)

type registerRequest struct {
	UserName     string `json:"name"`
	UserPassword string `json:"password"`
}

type loginRequest struct {
	UserName     string `json:"name"`
	UserPassword string `json:"password"`
}

// 实时语音翻译
func realtimeTranslateHandler(w http.ResponseWriter, r *http.Request) {
	asrModel.RealtimeTranslateHandler(w, r)
}

// 文本翻译
func textTranslateHandler(w http.ResponseWriter, r *http.Request) {
	textTranslateModel.TextTranslateHandler(w, r)
}

// 拍照翻译
func photoTranslateHandler(w http.ResponseWriter, r *http.Request) {
	ImageHandleModel.PhotoTranslateHandler(w, r)
}

func registerHandler(w http.ResponseWriter, r *http.Request) {
	log.Println("收到注册请求")
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
	w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
	if r.Method == "OPTIONS" {
		w.WriteHeader(http.StatusOK)
		return
	}

	var req registerRequest
	err := json.NewDecoder(r.Body).Decode(&req)
	if err != nil {
		http.Error(w, "解析请求体失败: "+err.Error(), http.StatusBadRequest)
		return
	}
	user := operateDB.User{
		Username:               req.UserName,
		Userpassword:           req.UserPassword,
		Status:                 1,
		IsVip:                  1,
		RegisterDate:           time.Now(),
		LoginDate:              time.Now(),
		OfflineDate:            time.Now(),
		UseNum:                 0,
		TextTranslateNum:       0,
		RealtimeTranslateNum:   0,
		RealtimeTranslateTimes: 100,
		TextTranslateTimes:     100,
	}
	lastInsertID, err := operateDB.InsertUser(user)
	if err != nil {
		log.Println(err)
	}
	fmt.Println(lastInsertID)

	_, err = w.Write([]byte("OK"))
	if err != nil {
		return
	}
	return
}

func loginHandler(w http.ResponseWriter, r *http.Request) {
	log.Println("收到登录请求")
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
	w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
	if r.Method == "OPTIONS" {
		w.WriteHeader(http.StatusOK)
		return
	}

	var req registerRequest
	err := json.NewDecoder(r.Body).Decode(&req)
	if err != nil {
		http.Error(w, "解析请求体失败: "+err.Error(), http.StatusBadRequest)
		return
	}
}

func InitMyServer() {
	// 注册路由
	http.HandleFunc("/textTranslate", textTranslateHandler)
	http.HandleFunc("/realtimeTranslate", realtimeTranslateHandler)

	http.HandleFunc("/photoTranslate", photoTranslateHandler)

	http.HandleFunc("/register", registerHandler)
	http.HandleFunc("/login", loginHandler)
	// 启动服务器
	log.Println("服务器启动在 :localhost:8081")
	log.Fatal(http.ListenAndServe(":8081", nil))
}
